# coding='utf-8'

from wand.image import Image
import os
import sys
import PyPDF2
import PythonMagick


class ManImage:
    
    
    def __init__(self, i_file, o_dire):
        """
        init args
        param i_file (str) input pdf file (eg homefile.pdf)
        param o_dire (str) output image directory (eg home)
        """
        
        
        self.i_file = i_file
        self.o_dire = o_dire
 
    def __str__(self):
        traceback = "Executing under {0.argv[0]} of {1.i_file} into {2.o_dire}.......format(sys, self, self)"
        return traceback
 
    def playpdf(self, ds):
        """
        split pdf file
        param ds (int) set ds = 1024 ~= 1MB output under my test
        return splited PNG image file
        """
        pages = PyPDF2.PdfFileReader(file(self.i_file, "rb")).getNumPages()
        print('Totally get {0^4} pages from {1.i_file}, playpdf start......'.format(pages, self))
        try:
            for i in range(pages):
                image = PythonMagick.Image()
                image.density(str(ds))
                image.read(self.i_file + '[' + str(i) + ']')
                image.magick("PNG")
                image.write(self.o_dire + str(i + 1) + ".png")
                print("{0:>5}     page OK......".format(i + 1))
        except Exception as e:
            print(str(e))

def pdf_to_img(path):

    base_name0 = os.path.basename(path)[:-4]
    dir_name = os.path.dirname(path)
    # base_name1 = os.path.basename(dir_name)
    new_dir = os.path.join(dir_name, base_name0)
    if not os.path.exists(new_dir):
        os.makedirs(new_dir)

    with Image(filename=path, resolution=300) as img:
        with img.convert('jpg') as converted:
            converted.save(filename=os.path.join(new_dir, 'page.jpg'))


# def fast_pdf2jpg():
#     pdf = file(sys.argv[1], "rb").read()

#     startmark = "\xff\xd8"
#     startfix = 0
#     endmark = "\xff\xd9"
#     endfix = 2
#     i = 0

#     njpg = 0
#     while True:
#         istream = pdf.find("stream", i)
#         if istream < 0:
#             break
#         istart = pdf.find(startmark, istream, istream+20)
#         if istart < 0:
#             i = istream+20
#             continue
#         iend = pdf.find("endstream", istart)
#         if iend < 0:
#             raise Exception("Didn't find end of stream!")
#         iend = pdf.find(endmark, iend-20)
#         if iend < 0:
#             raise Exception("Didn't find end of JPG!")
        
#         istart += startfix
#         iend += endfix
#         print "JPG %d from %d to %d" % (njpg, istart, iend) 
#         jpg = pdf[istart:iend]
#         jpgfile = file("jpg%d.jpg" % njpg, "wb")
#         jpgfile.write(jpg)
#         jpgfile.close()
        
#         njpg += 1
#         i = iend

# def pdf_to_img1(path):
#     try:
#         base_name0 = os.path.basename(path)[:-4]
#         dir_name = os.path.dirname(path)
#         # base_name1 = os.path.basename(dir_name)
#         new_dir = os.path.join(dir_name, base_name0)
#         if not os.path.exists(new_dir):
#             os.makedirs(new_dir)

#         with Image(filename=path, resolution=300) as img:
#             with img.convert('jpg') as converted:
#                 converted.save(filename=os.path.join(new_dir, 'page.jpg'))
#     except:
#         with open(os.path.join(new_dir, 'error.txt'),'w') as error_f:
#             error_f.write('error')

if __name__ == '__main__':
    path_dir = sys.argv[1]
    for p in os.listdir(path_dir):
        path = path_dir + os.sep + p
        pdf_to_img(path)



# from __future__ import print_function
# from wand.image import Image
# import os
# import sys
# from docx import Document

# count = 0
# new_dir = r'C:\Users\vanlance\Desktop\ninbo\all_out'


# def to_img(path):
#     # base_name0 = os.path.basename(path)[:-4]
#     # dir_name = os.path.dirname(path)
#     # base_name1 = os.path.basename(dir_name)
#     new_dir = r'./pic'
#     if not os.path.exists(new_dir):
#         os.makedirs(new_dir)

#     with Image(filename=path,resolution=300) as img:

#         with img.convert('jpg') as converted:
           
#             # with open('a.jpg', 'wb') as wf:
#             #     print(help(converted.sequence[0]))
#                 # wf.write(converted.sequence[0])
#             # with open(os.path.join(new_dir, 'page_num.txt'),'w') as wf:
#             #     wf.write(str(len(converted.sequence)))
#             converted.save(filename=new_dir + '/page.jpg')


# def to_img11(path):
#     global count
#     # base_name0 = os.path.hbasename(path)[:-4]
#     # dir_name = os.path.dirname(path)
#     # base_name1 = os.pat.basename(dir_name)
#     # new_dir = os.path.join(dir_name, base_name0)
#     # if not os.path.exists(new_dir):
#     #     os.makedirs(new_dir)

#     with Image(filename=path,resolution=300) as img:

#         with img.convert('jpg') as converted:
#             # with open(os.path.join(new_dir, 'page_num.txt'),'w') as wf:
#             #     wf.write(str(len(converted.sequence)))
#             converted.save(filename=path[:-4] + '_page.jpg')
#         count += 1


# def main(dir_path):
    
#     paths_1 = [os.path.join(dir_path, p)  for p in os.listdir(dir_path) if os.path.isdir(os.path.join(dir_path, p))]
#     paths_3 = [os.path.join(ff, p)  for ff in paths_1 for p in os.listdir(ff) if os.path.isdir(os.path.join(ff, p))]
#     paths_2 = [os.path.join(p, f) for p in paths_3 for f in os.listdir(p) if f.split('.')[-1].upper() == 'PDF']
#     for path in paths_2:
#         to_img11(path)
#         print(path)

# def main1(dir_path):
#     paths_1 = [os.path.join(dir_path, p)  for p in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, p))]
#     for p in paths_1:
#         to_img11(p)

# if __name__ == '__main__':
#     i_file = sys.argv[1]
#     main1(i_file)
